import { Component, ChangeDetectorRef, ChangeDetectionStrategy, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { KeyIssuesModel } from '../../templates/keyIssues/keyIssues.model';
import { CompanyRiskRatingService } from '../../companyRiskRating.service';
import { HttpClient } from '@angular/common/http';
import { Subscription } from 'rxjs/Subscription';
import { UtilsService } from '../../../../../../shared/services/utils.service';
import { environment } from '../../../../../../../environments/environment';
import { ChartColumnModel } from '../../../shared/companyIndicator/models/chartColumn.model';
import { AnalyticsService } from '../../../../../../shared/services/googleAnalytics.service';
import * as _ from 'lodash';
import { ClusterService } from '../../../../riskCluster/cluster.service';


/**
 * MEI indicators component
 *
 * Author: Sorin Spiru
 * Date: 16.01.2018
 */
@Component({
    selector: 'mei-indicators',
    templateUrl: '../../templates/indicators/indicators.component.html',
    styleUrls: ['../../templates/indicators/indicators.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class MeiIndicatorsComponent extends KeyIssuesModel {
    private sub: Subscription;
    private companySub: Subscription;
    private fragSub: Subscription;
    private scrolled: boolean = false;

    public companyId: string;
    public externalId: number;
    //company indicator module context does not have access to BaseHttpService and http requests do not know the serviceUrl. We specify this
    public serviceUrl: string = environment.serviceUrl;
    public selectedIndicator = undefined;
    public totalScore: number;
    public indentPercentile: number;
    @Input() type: string;
    @Input() isCore = false;

    constructor(
        private route: ActivatedRoute,
        private cdRef: ChangeDetectorRef,
        private riskService: CompanyRiskRatingService,
        public analyticsService: AnalyticsService,
        public http: HttpClient        
    ) {
        super(cdRef);

        this.currentComponent = "meiIndicators";
        this.headerPercentWidth = 30;
        this.showLimit = false;
    }

    ngOnInit() {
        this.sub = this.route.params.subscribe(_ => {
            this.load();
        });

        this.fragSub = this.route.fragment.subscribe(fragment => {
            this.indicatorToExpand = fragment;
        });

    }

    ngOnDestroy() {
        this.elements = [];
        this.sub.unsubscribe();
        this.fragSub.unsubscribe();
        if(this.companySub) this.companySub.unsubscribe();
    }

    ngAfterContentChecked() {
        if(this.scrolled == false && this.indicatorToExpand){
            let elem: HTMLElement = document.getElementById(this.indicatorToExpand);
            if(elem)
            {
                //wait for expand
                setTimeout(() => {
                    elem.scrollIntoView({behavior:"smooth"});
                    this.scrolled = true;
                }, 500);
            }
        }
    }

    private load(): void {
        this.loaded = new Promise<void>((resolve, reject) => {
            this.companySub = this.riskService.company.subscribe(company => {                
                this.companyId = company.id;
                this.totalScore = company.managementRisk;
                if (this.isCore) {
                    this.getIndicatorDetails = this.riskService.getIndicatorByCode;
                    this.columns = [
                        new ChartColumnModel('Raw Score', 20, 100, 'score', false, '#B3D4D1', true, false, true, '', null, 0),
                        new ChartColumnModel('Weight', 20, 100, 'weight', false, '#B5B7B7', true, false, true, '%', null, 1),
                        new ChartColumnModel('Weighted Score', 30, 20, 'weightedScore', false, 'black', true, true, true, '', null, 1)
                    ];
                    
                    this.riskService.getCoreIndentPercentile(this.companyId).subscribe(data => {  
                        this.indentPercentile = UtilsService.formatIssueWeight(data);
                        this.cdRef.markForCheck();
                    }, _ => this.errorCallback(_ => this.errorReset(), undefined));

                    this.elements = this.setupIndicators(company['indicators']);

                    this.elements = _.orderBy(this.elements,
                    ['indicatorType','category'],               
                    ['asc', 'desc']);

                    this.cdRef.markForCheck();
                    resolve();
                } else {
                    this.getIndicatorDetails = this.riskService.getMEIIndicatorByCode;
                    this.riskService.mei.subscribe(mei => {                        
                        this.mei = mei;                        
                        this.externalId = mei.externalId;
                        this.meiType = mei.type;
                        this.totalScore = mei.management;

                        this.columns = [
                            new ChartColumnModel(mei.type == 'BaselineIssue' ? 'Pillar Score' : 'Raw Score', 20, 100, 'score', false, '#B3D4D1', true, false, true, '', null, 0),
                            new ChartColumnModel('Weight', 20, 100, 'weight', false, '#B5B7B7', true, false, true, '%', null, 1),
                            new ChartColumnModel('Weighted Score', 30, 20, 'weightedScore', false, 'black', true, true, true, '', null, 1)
                        ];

                        this.elements = this.setupIndicators(this.mei.indicators);
                        this.cdRef.markForCheck();
                        resolve();
                    }, _ => this.errorCallback(_ => this.errorReset(), undefined));
                }
            });
        });
    }

    getCategoryIcon(indicator) {
        return UtilsService.getIconFilename('icon-cat' + indicator.category);
    }

    isEventIndicator(indicator) {
        return indicator.indicatorType === 1;
    }

    private setupIndicators( indicators ) {
        return indicators.map(indicator => {
            return {
                name: indicator.name,
                code: indicator.code,
                indicatorType: indicator.indicatorType,
                category: indicator.category,
                score: { value: indicator.rawScore },
                weight: { value: UtilsService.formatIssueWeight( this.isCore ? indicator.finalWeight : indicator.weightInMei) },
                weightedScore: { value: (this.isCore ? indicator.weightedScore : indicator.weightedScoreInMei) || 0 },
                isMain: true
            };
        });
    }
}
